package com.ruoyi.system.controller;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IOaAccountsReceivableSummaryService;
import com.ruoyi.system.service.IOaProjectInitiationService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.IOaInvoiceApplicationService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 发票开具申请单Controller
 *
 * @author ruoyi
 * @date 2025-03-14
 */
@RestController
@RequestMapping("/system/application")
@Transactional
public class OaInvoiceApplicationController extends BaseController {
    @Autowired
    private IOaInvoiceApplicationService oaInvoiceApplicationService;
    @Autowired
    private IOaProjectInitiationService oaProjectInitiationService;
    @Autowired
    private IOaAccountsReceivableSummaryService oaAccountsReceivableSummaryService;

    /**
     * 查询发票开具申请单列表
     */
    @PreAuthorize("@ss.hasPermi('system:application:list')")
    @GetMapping("/list")
    public TableDataInfo list(OaInvoiceApplication oaInvoiceApplication) {
        startPage();
        List<OaInvoiceApplication> list = oaInvoiceApplicationService.selectOaInvoiceApplicationList(oaInvoiceApplication);
        return getDataTable(list);
    }

    /**
     * 导出发票开具申请单列表
     */
    @PreAuthorize("@ss.hasPermi('system:application:export')")
    @Log(title = "发票开具申请单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OaInvoiceApplication oaInvoiceApplication) {
        List<OaInvoiceApplication> list = oaInvoiceApplicationService.selectOaInvoiceApplicationList(oaInvoiceApplication);
        ExcelUtil<OaInvoiceApplication> util = new ExcelUtil<OaInvoiceApplication>(OaInvoiceApplication.class);
        util.exportExcel(response, list, "发票开具申请单数据");
    }

    /**
     * 获取发票开具申请单详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:application:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(oaInvoiceApplicationService.selectOaInvoiceApplicationById(id));
    }

    /**
     * 新增发票开具申请单
     */
    @PreAuthorize("@ss.hasPermi('system:application:add')")
    @Log(title = "发票开具申请单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OaInvoiceApplication oaInvoiceApplication) {
        Long projectId = oaInvoiceApplication.getProjectId();
        OaAccountsReceivableSummary oaAccountsReceivableSummary = new OaAccountsReceivableSummary();
        oaAccountsReceivableSummary.setProjectId(projectId);
        List<OaAccountsReceivableSummary> oaAccountsReceivableSummaries = oaAccountsReceivableSummaryService.selectOaAccountsReceivableSummaryList(oaAccountsReceivableSummary);
        for (OaAccountsReceivableSummary summary : oaAccountsReceivableSummaries) {
            if (summary.getIsPaid() == 1) {
                throw new RuntimeException("该立项已有应收汇总已回款，无法新增发票开具申请单");
            }
        }
        int i = oaInvoiceApplicationService.insertOaInvoiceApplication(oaInvoiceApplication);
        return toAjax(i);
    }

    /**
     * 修改发票开具申请单
     */
    @PreAuthorize("@ss.hasPermi('system:application:edit')")
    @Log(title = "发票开具申请单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OaInvoiceApplication oaInvoiceApplication) {
        return toAjax(oaInvoiceApplicationService.updateOaInvoiceApplication(oaInvoiceApplication));
    }

    /**
     * 删除发票开具申请单
     */
    @PreAuthorize("@ss.hasPermi('system:application:remove')")
    @Log(title = "发票开具申请单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(oaInvoiceApplicationService.deleteOaInvoiceApplicationByIds(ids));
    }
    //吕昊发票审核页面数据

    @GetMapping("/list1")
    public TableDataInfo list1(Long id) {
        OaInvoiceApplication oaInvoiceApplication = new OaInvoiceApplication();
        oaInvoiceApplication.setIsApproved(0);
        oaInvoiceApplication.setProjectId(id);
        List<OaInvoiceApplication> list = oaInvoiceApplicationService.selectOaInvoiceApplicationList(oaInvoiceApplication);
        return getDataTable(list);
    }
    @GetMapping("/listA")
    public TableDataInfo list2(OaInvoiceApplication oaInvoiceApplication) {
        oaInvoiceApplication.setIsApproved(0);
        List<OaInvoiceApplication> list = oaInvoiceApplicationService.selectOaInvoiceApplicationList(oaInvoiceApplication);
        ArrayList<OaProjectInitiation> oaProjectInitiations1 = new ArrayList<>();
        for (OaInvoiceApplication application : list) {
            OaProjectInitiation oaProjectInitiation = new OaProjectInitiation();
            oaProjectInitiation.setId(application.getProjectId().intValue());
            List<OaProjectInitiation> oaProjectInitiations = oaProjectInitiationService.selectOaProjectInitiationList(oaProjectInitiation);
            oaProjectInitiations1.addAll(oaProjectInitiations);
        }
        for (OaProjectInitiation initiation : oaProjectInitiations1) {
            System.out.println(initiation.getId()+"====");
        }
        Map<Integer, OaProjectInitiation> map = new LinkedHashMap<>();
        for (OaProjectInitiation initiation : oaProjectInitiations1) {
            if (!map.containsKey(initiation.getId())) {
                map.put(initiation.getId(), initiation);
            }
        }
        List<OaProjectInitiation> distinctInitiations = new ArrayList<>(map.values());
        return getDataTable(distinctInitiations);
    }
    //吕昊发票批量审核
    @GetMapping("/audit")
    public AjaxResult audit(@RequestParam("ids")Long[] ids) {
        if (ids == null || ids.length == 0) {
            return AjaxResult.error("未提供有效的 ID 列表");
        }
        for (Long id : ids) {
            OaInvoiceApplication oaInvoiceApplication = oaInvoiceApplicationService.selectOaInvoiceApplicationById(id);
            if (oaInvoiceApplication != null) {
                oaInvoiceApplication.setIsApproved(1);
                oaInvoiceApplication.setDataapp(new Date());
                oaInvoiceApplicationService.updateOaInvoiceApplication(oaInvoiceApplication);
                summaryGenerator(oaInvoiceApplication.getProjectId().toString());
                Long projectId = oaInvoiceApplication.getProjectId();
                OaProjectInitiation oaProjectInitiation = oaProjectInitiationService.selectOaProjectInitiationById(projectId.intValue());
                oaProjectInitiation.setInvoiceStatus("是");
                oaProjectInitiationService.updateOaProjectInitiation(oaProjectInitiation);
            }
        }
        return AjaxResult.success("审核成功");
    }

    //生成应付收账汇总信息
    public void summaryGenerator(String id) {
        //创建OaAccountsReceivableSummary对象
        OaAccountsReceivableSummary oaAccountsReceivableSummary = new OaAccountsReceivableSummary();
        //设置项目ID
        oaAccountsReceivableSummary.setProjectId(Long.valueOf(id));
        //查询项目ID对应的应付收账汇总信息
        List<OaAccountsReceivableSummary> oaAccountsReceivableSummaries = oaAccountsReceivableSummaryService.selectOaAccountsReceivableSummaryList(oaAccountsReceivableSummary);
        //遍历查询结果
        for (OaAccountsReceivableSummary summary : oaAccountsReceivableSummaries) {
            //删除查询结果中的应付收账汇总信息
            oaAccountsReceivableSummaryService.deleteOaAccountsReceivableSummaryById(summary.getId());
        }
        //根据项目ID查询项目发起信息
        OaProjectInitiation oaProjectInitiation = oaProjectInitiationService.selectOaProjectInitiationById(Integer.valueOf(id));
        //创建OaInvoiceApplication对象
        OaInvoiceApplication oaInvoiceApplication1 = new OaInvoiceApplication();
        //设置项目ID
        oaInvoiceApplication1.setProjectId(Long.valueOf(id));
        oaInvoiceApplication1.setIsApproved(1);
        //查询项目ID对应的发票申请信息
        List<OaInvoiceApplication> oaInvoiceApplications1 = oaInvoiceApplicationService.selectOaInvoiceApplicationList(oaInvoiceApplication1);
        //遍历查询结果
        for (OaInvoiceApplication application : oaInvoiceApplications1) {
            //创建OaAccountsReceivableSummary对象
            OaAccountsReceivableSummary oaAccountsReceivableSummary1 = new OaAccountsReceivableSummary();
            oaAccountsReceivableSummary1.setClientInvoiceName(oaProjectInitiation.getSecondaryCompany());
            //设置项目编号
            oaAccountsReceivableSummary1.setProjectNumber(oaProjectInitiation.getProjectNumber());
            //设置项目名称
            oaAccountsReceivableSummary1.setProjectName(oaProjectInitiation.getProjectContent());
            //设置已开票金额
            oaAccountsReceivableSummary1.setInvoicedAmount(application.getInvoicedAmount());
            //判断发票申请信息中的dataapp是否为空
            if (application.getDataapp() != null) {
                //设置发票日期
                oaAccountsReceivableSummary1.setInvoiceDate(application.getDataapp());
                //设置是否已开票
                oaAccountsReceivableSummary1.setIsInvoiced(1);
            } else {
                //设置是否已开票
                oaAccountsReceivableSummary1.setIsInvoiced(0);
            }
            //设置项目ID
            oaAccountsReceivableSummary1.setProjectId(Long.valueOf(id));
            oaAccountsReceivableSummary.setIsPaid(0);
            //设置项目负责人
            oaAccountsReceivableSummary1.setProjectLeader(oaProjectInitiation.getInitiationPersonInCharge());
            //插入应付收账汇总信息
            oaAccountsReceivableSummaryService.insertOaAccountsReceivableSummary(oaAccountsReceivableSummary1);
        }

    }

    @GetMapping("/received")
    //是否回款按钮
    public AjaxResult received(String id, String received) {
        OaAccountsReceivableSummary oaAccountsReceivableSummary = oaAccountsReceivableSummaryService.selectOaAccountsReceivableSummaryById(Long.valueOf(id));
        if (received.equals("已回款")) {
            oaAccountsReceivableSummary.setIsPaid(1);
            oaAccountsReceivableSummaryService.updateOaAccountsReceivableSummary(oaAccountsReceivableSummary);
            return AjaxResult.success("已回款");
        }
        oaAccountsReceivableSummary.setIsPaid(0);
        oaAccountsReceivableSummaryService.updateOaAccountsReceivableSummary(oaAccountsReceivableSummary);
        return AjaxResult.success("未回款");
    }

    //发票开具类型申请单批量添加
    @PostMapping("/adds")
    public AjaxResult adds(@RequestBody List<OaInvoiceApplication> oaOtheraPurchases) {
        for (OaInvoiceApplication other : oaOtheraPurchases) {
            Long projectId = other.getProjectId();
            OaAccountsReceivableSummary oaAccountsReceivableSummary = new OaAccountsReceivableSummary();
            oaAccountsReceivableSummary.setProjectId(projectId);
            List<OaAccountsReceivableSummary> oaAccountsReceivableSummaries = oaAccountsReceivableSummaryService.selectOaAccountsReceivableSummaryList(oaAccountsReceivableSummary);
            for (OaAccountsReceivableSummary summary : oaAccountsReceivableSummaries) {
                if (summary.getIsPaid() == 1) {
                    throw new RuntimeException("该立项已有应收汇总已回款，无法新增发票开具申请单");
                }
            }
            List<OaInvoiceApplication> oaInvoiceApplications = oaInvoiceApplicationService.selectOaInvoiceApplicationList(other);
            if (!oaInvoiceApplications.isEmpty()) {
                continue;
            }
            oaInvoiceApplicationService.insertOaInvoiceApplication(other);
        }
        return AjaxResult.success("批量添加成功");
    }

    //发票开具类型申请单批量修改
    @PutMapping("/edits")
    public AjaxResult edits(@RequestBody List<OaInvoiceApplication> oaOtheraPurchases) {
        for (OaInvoiceApplication other : oaOtheraPurchases) {
            oaInvoiceApplicationService.updateOaInvoiceApplication(other);
        }
        return AjaxResult.success("批量修改成功");
    }

    @GetMapping("/list2")
    public TableDataInfo list2(Long id) {
        OaInvoiceApplication oaInvoiceApplication = new OaInvoiceApplication();
        oaInvoiceApplication.setProjectId(id);
        List<OaInvoiceApplication> list = oaInvoiceApplicationService.selectOaInvoiceApplicationList(oaInvoiceApplication);
        return getDataTable(list);
    }
}
